package org.catspaw.cherubim.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.pragmindz.hessian.model.HessianValue;
import org.pragmindz.hessian.parser.HessianParser;
import org.pragmindz.hessian.parser.HessianParserException;
import org.pragmindz.hessian.parser.HessianRenderException;
import org.pragmindz.hessian.serializer.HessianSerializer;
import org.pragmindz.hessian.serializer.HessianSerializerException;

public class Hessian4jSerializer implements Serializer {

	private static final HessianSerializer	serializer	= new HessianSerializer();

	public byte[] serialize(Object obj) {
		if (obj == null) {
			return null;
		}
		HessianValue value;
		try {
			value = serializer.serialize(obj);
		} catch (HessianSerializerException e) {
			throw new IllegalArgumentException(e);
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			value.render(baos);
		} catch (HessianRenderException e) {
			throw new IllegalArgumentException(e);
		}
		return baos.toByteArray();
	}

	public Object deserialize(byte[] bs) {
		if (bs == null) {
			return null;
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(bs);
		HessianParser parser = new HessianParser(bais);
		HessianValue value;
		try {
			value = parser.nextValue();
		} catch (HessianParserException e) {
			throw new IllegalArgumentException(e);
		}
		try {
			return serializer.deserialize(value);
		} catch (HessianSerializerException e) {
			throw new IllegalArgumentException(e);
		}
	}
}
